#include <signal.h>

#include <iostream>
using std::cout;
using std::endl;

#include <workflow/WFFacilities.h>
#include <workflow/WFHttpServer.h>
#include <workflow/HttpUtil.h>
#include <workflow/HttpMessage.h>


//通过构造函数初始化计数器的值 
static WFFacilities::WaitGroup waitGroup(1);

void sighandler(int num)
{
    printf("sig %d is coming\n", num);
    //将计数器的值减1
    waitGroup.done();
}

void httpCallback(WFHttpTask * )
{
    printf("httpCallback is running.\n");
}

void process(WFHttpTask * serverTask)
{
    printf("process is running.\n");
    //0. 设置任务的回调函数
    serverTask->set_callback(httpCallback);
    //1. 对任务的状态进行检测
    int state = serverTask->get_state();
    printf("state: %d\n", state);
    int error = serverTask->get_error();
    if(state != WFT_STATE_TOREPLY) {
        printf("error ocurrs: %s\n", WFGlobal::get_error_string(state, error));
        return;
    }
    //2. 解析请求
    auto req = serverTask->get_req();
    //2.1 打印起始行
    printf("%s %s %s\n", req->get_method(),
           req->get_request_uri(),
           req->get_http_version());
    //2.2 打印首部字段
    protocol::HttpHeaderCursor cursor(req);
    std::string key,val;
    while(cursor.next(key, val)) {
        cout << key << ": " << val << endl;
    }
    cout << endl;

    //3. 生成响应
    auto resp = serverTask->get_resp();
    resp->add_header_pair("Content-Type", "text/html");
    resp->append_output_body("<html><body>hello,client</body></html>");
}

void test0()
{
    signal(SIGINT, sighandler);

    WFHttpServer httpServer(process);
    
    if(httpServer.start(8888) == 0) {
        waitGroup.wait();
        httpServer.stop();
    }

    waitGroup.wait();
}


int main()
{
    test0();
    printf("exit main\n");
    return 0;
}

